package pers.qianyu.month_202012.date_20201218;

import org.junit.*;

import java.util.*;

/**
 * 560. 和为K的子数组
 * https://leetcode-cn.com/problems/subarray-sum-equals-k/
 *
 * @author mizzle rain
 * @date 2020-12-18 21:54
 */
public class SubarraySum {
    public int subarraySum(int[] nums, int k) {
        int len = nums.length;
        if (len == 0) {
            return 0;
        }
        int[] preSum = new int[len + 1];
        for (int i = 0; i < nums.length; i++) {
            preSum[i + 1] = nums[i] + preSum[i];
        }
        int res = 0;
        for (int i = preSum.length - 1; i > 0; i--) {
            for (int j = i - 1; j >= 0; j--) {
                if (preSum[i] - preSum[j] == k) {
                    res++;
                }
            }
        }
        return res;
    }

    public int subarraySum2(int[] nums, int k) {
        // 前缀数组完成之后，可以转换为数组中，两数之差为 k 的组合个数
        int pre = 0, res = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int v : nums) {
            pre += v;
            if (map.containsKey(pre - k)) {
                res += map.get(pre - k);
            }
            map.put(pre, map.getOrDefault(pre, 0) + 1);
        }
        return res;
    }

    @Test
    public void test1() {
        int result = new SubarraySum().subarraySum(new int[]{1, 1, 1}, 2);
        System.out.println("result = " + result);
    }
}
